package com.xbongbong.crm.perform.query.detail;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmDetailBaseInfoService;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.data.service.RichTextService;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.help.OwnerAndCoUserHelp;
import com.xbongbong.paas.pojo.vo.FormDataGetVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.parent.explain.FormDataDetailFormExplainHandleName;
import com.xbongbong.parent.parse.data.FormDataGetAnalysisDataHelp;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.saas.domain.entity.WorkPlanEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.WorkReportDailyEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.saas.enums.business.WorkReportPlanEnum;
import com.xbongbong.saas.model.WorkReportModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author sunshaoxiang
 * @ClassName WorkReportDetailBaseInfoServiceImpl
 * @Description 工作报告详情页 基本信息 业务层
 * @Date 2022/6/13 9:31
 * @Version 1.0
 **/
@Service("workReportDetailBaseInfoServiceImpl")
public class WorkReportDetailBaseInfoServiceImpl extends AbstractCrmDetailBaseInfoService {

    public static final Logger LOGGER = LoggerFactory.getLogger(WorkReportDetailBaseInfoServiceImpl.class);

    @Resource
    private WorkReportModel workReportModel;
    @Resource
    private OwnerAndCoUserHelp ownerAndCoUserHelp;
    @Resource
    private FormDataDetailFormExplainHandleName formDataDetailFormExplainHandleName;
    @Resource
    private UserModel userModel;
    @Resource
    private FormDataGetAnalysisDataHelp formDataGetAnalysisDataHelp;
    @Resource
    private RichTextService richTextService;
    @Resource
    private FormDataHelp formDataHelp;

    @Override
    public List<Integer> businessType() {
        return Collections.singletonList(XbbRefTypeEnum.WORK_REPORT.getCode());
    }

    @Override
    public void checkPermission(PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, UserVO loginUser, Integer subBusinessType) throws XbbException {

    }

    @Override
    public HandlerExplainVO handleExplain(List<FieldAttrEntity> explainList, PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        // 移动端工作报告详情基本信息不展示业绩数据
        explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), WorkReportFieldEnum.THIS_STATISTIC.getAttr()));
        handlerExplainDTO.setExplainList(explainList);
        ownerAndCoUserHelp.getOwnerIdAndCoUserId(handlerExplainDTO, handlerExplainDTO.getSaasMark(), handlerExplainDTO.getBusinessType(), paasFormDataEntityExt, new HashMap<>(), DelEnum.NORMAL.getDel());
        HandlerExplainVO handlerExplainVO = formDataDetailFormExplainHandleName.handleExplain(explainList, formEntity, paasFormDataEntityExt, handlerExplainDTO);

        FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
        BeanUtil.copyProperties(handlerExplainDTO, formatExplainDTO);
        formatExplainDTO.setExplainList(explainList);
        formatExplainDTO.setResult(paasFormDataEntityExt.getData());
        formatExplainDTO.setDataEntity(paasFormDataEntityExt);
        workReportModel.formatUpdateExplain(formatExplainDTO);
        return handlerExplainVO;
    }

    @Override
    public JSONObject analysisData(PaasFormDataEntityExt paasFormDataEntityExt, HandlerExplainDTO handlerExplainDTO, HandlerExplainVO handlerExplainVO) throws XbbException {
        List<FieldAttrEntity> list = handlerExplainVO.getHeadList();
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(list.size());
        String corpid = handlerExplainDTO.getCorpid();
        Integer businessType = handlerExplainDTO.getBusinessType();
        Long formId = paasFormDataEntityExt.getFormId();
        List<FieldAttrEntity> headList = handlerExplainVO.getHeadList();
        String platform = handlerExplainDTO.getPlatform();
        Long dataId = paasFormDataEntityExt.getId();
        String creatorId = paasFormDataEntityExt.getCreatorId();
        list.forEach(item->explainMap.put(item.getAttr(), item));
        // 工作报告的今日计划，明日计划重新取
        reSetPlanToData(paasFormDataEntityExt, handlerExplainDTO.getCorpid());
        //todo 这里和commonAnalysisData 的位置换了。回头需要确认一下有没有影响
        SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
        BeanUtil.copyProperties(handlerExplainDTO, saasAnalysisDataDTO);
        saasAnalysisDataDTO.setFormId(formId);
        saasAnalysisDataDTO.setUserId(creatorId);
        workReportModel.formatData(saasAnalysisDataDTO, paasFormDataEntityExt.getData());

        //通用解析
        JSONObject data = commonAnalysisAllData(paasFormDataEntityExt, handlerExplainDTO, handlerExplainVO, list, explainMap);

        return data;
    }

    @Override
    public PaasFormDataEntityExt getData(Integer businessType, Integer subBusinessType, Integer saasMark, String corpid, Long dataId, Long formId) throws XbbException {
        PaasFormDataEntityExt formData = formDataHelp.getFormData(dataId, corpid, businessType);
        if (Objects.isNull(formData)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        FormDataUtil.checkData(formData, subBusinessType);
        //拼装富文本数据
        richTextService.addRichTextByDataId(dataId, corpid, formData.getFormId(), subBusinessType, saasMark, formData.getDel(), formData.getData());
        return formData;
    }

    /**
     * 工作报告的今日计划，明日计划重新取
     * @param paasFormDataEntityExt
     * @param corpid
     */
    private void reSetPlanToData(PaasFormDataEntityExt paasFormDataEntityExt, String corpid) throws XbbException {
        JSONObject data = paasFormDataEntityExt.getData();
        List<WorkPlanEntity> thisPlanList = workReportModel.getThisPlansByTime(corpid, paasFormDataEntityExt.getCreatorId(),
                FastJsonHelper.getIntegerFromFormData(data, WorkReportFieldEnum.TYPE.getAttr()),
                FastJsonHelper.getIntegerFromFormData(data, WorkReportFieldEnum.REPORT_DATE.getAttr()));
        JSONArray thisPlan = new JSONArray();
        for (WorkPlanEntity entity : thisPlanList) {
            JSONObject object = new JSONObject();
            object.put(WorkReportPlanEnum.CONTENT.getAttr(), entity.getContent());
            object.put(WorkReportPlanEnum.STATUS.getAttr(), entity.getStatus());
            object.put(WorkReportPlanEnum.ID.getAttr(), entity.getId());
            thisPlan.add(object);
        }
        List<WorkPlanEntity> nextPlanList = workReportModel.getNextPlansByTime(corpid, paasFormDataEntityExt.getCreatorId(),
                FastJsonHelper.getIntegerFromFormData(data, WorkReportFieldEnum.TYPE.getAttr()), paasFormDataEntityExt.getId());
        JSONArray nextPlan = new JSONArray();
        for (WorkPlanEntity entity : nextPlanList) {
            JSONObject object = new JSONObject();
            object.put(WorkReportPlanEnum.CONTENT.getAttr(), entity.getContent());
            object.put(WorkReportPlanEnum.ID.getAttr(), entity.getId());
            nextPlan.add(object);
        }

        data.put(WorkReportFieldEnum.THIS_PLAN.getAttr(), thisPlan);
        data.put(WorkReportFieldEnum.NEXT_PLAN.getAttr(), nextPlan);
    }

    @Override
    public FormDataGetVO returnVo(PaasFormDataEntityExt formData, HandlerExplainVO handlerExplainVO, JSONObject data, PaasFormEntityExt form, String userId, String corpid) throws XbbException {
        FormDataGetVO formDataGetVO = new FormDataGetVO();
        formDataGetVO.setPaasFormEntity(form);
        formDataGetVO.setHeadList(ExplainUtil.getFieldListWorkReport(handlerExplainVO).getHeadList());
        formDataGetVO.setData(data);
        formDataGetVO.setSaasObj(getSaasReturnObj(data, formData.getId(), userId, corpid));
        return formDataGetVO;
    }

    private JSONObject getSaasReturnObj(JSONObject data, Long dataId, String userId, String corpid) throws XbbException {
        JSONObject saasReturnObj = new JSONObject();
        JSONArray reviewerArray;
        try {
            reviewerArray = JSONArray.parseArray(data.getString(WorkReportFieldEnum.REVIEWER.getAttr()));
            reviewerArray = reviewerArray == null ? new JSONArray() : reviewerArray;
        }catch (Exception e){
            reviewerArray = new JSONArray();
        }
        Boolean needUpdate = true;
        for (Object obj : reviewerArray){
            JSONObject json = (JSONObject) obj;
            if (Objects.equals(json.getString("userId"), userId)){
                needUpdate = false;

                break;
            }
        }
        if (needUpdate){
            // 只有手机端会调用，pc端会先调用pro/v1/workReport/detail
            UserEntity userEntity = userModel.getByKey(userId,corpid);
            JSONObject json = new JSONObject();
            json.put("userId",userEntity.getUserId());
            json.put("name",userEntity.getName());
            json.put("avatar",userEntity.getAvatar());
            reviewerArray.add(json);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(WorkReportFieldEnum.REVIEWER.getAttr(), reviewerArray.toJSONString());
            // 更新时间使用数据里的时间
            UpdateDataEntity updateData = ExplainUtil.getUpdateData(dataId, jsonObject, corpid, data.getLong(FieldTypeEnum.UPDATETIME.getAlias()));
            workReportModel.updateBatch(Collections.singletonList(updateData), corpid);
        }
        saasReturnObj.put(WorkReportDailyEnum.REVIEWER.getAttr(), reviewerArray);
        return saasReturnObj;
    }
}
